package cn.iocoder.yudao.module.product.category.controller.admin;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.api.shop.info.dto.ShopInfoDTO;
import cn.iocoder.yudao.module.product.category.dal.dataobject.ProductCategoryDO;
import cn.iocoder.yudao.module.product.category.service.ProductCategoryService;
import cn.iocoder.yudao.module.product.category.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserLastShopId;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.isSuperAdmin;

@Tag(name = "管理后台 - 产品分类")
@RestController
@RequestMapping("/product/category")
@Validated
public class ProductCategoryController {

    @Resource
    private ProductCategoryService productCategoryService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @PostMapping("/create")
    @Operation(summary = "创建产品分类")
    @PreAuthorize("@ss.hasRole('shop_admin')")
    public CommonResult<Long> createCategory(@Valid @RequestBody ProductCategorySaveReqVO createReqVO) {
        return success(productCategoryService.createCategory(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新产品分类")
    @PreAuthorize("@ss.hasPermission('product:category:update')")
    public CommonResult<Boolean> updateCategory(@Valid @RequestBody ProductCategorySaveReqVO updateReqVO) {
        productCategoryService.updateCategory(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除产品分类")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasRole('shop_admin')")
    public CommonResult<Boolean> deleteCategory(@RequestParam("id") Long id) {
        productCategoryService.deleteCategory(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得产品分类")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<ProductCategoryRespVO> getCategory(@RequestParam("id") Long id) {
        ProductCategoryDO category = productCategoryService.getCategory(id);
        return success(BeanUtils.toBean(category, ProductCategoryRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得产品分类分页")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<PageResult<ProductCategoryRespVO>> getCategoryPage(@Valid ProductCategoryPageReqVO pageVO) {
        PageResult<ProductCategoryDO> pageResult = productCategoryService.getCategoryPage(pageVO);
        List<ProductCategoryRespVO> data = dosToVOS(pageResult.getList());
        return success(new PageResult<>(data, pageResult.getTotal()));
    }

    @GetMapping("/list")
    @Operation(summary = "获得产品分类列表")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<List<ProductCategoryRespVO>> getCategoryList(@Valid ProductCategoryListReqVO listReqVO) {
        List<ProductCategoryDO> list = new ArrayList<>();
        Long shopId = getLoginUserLastShopId();
        if (shopId != null && shopId > 0) {
            list.addAll(productCategoryService.getDescendentCategoryList(shopId, new HashSet<>(), CommonStatusEnum.ENABLE.getStatus()));
        } else if (isSuperAdmin()) {
            list.addAll(productCategoryService.getCategoryList(listReqVO));
        }
        return success(dosToVOS(list));
    }

    @Nonnull
    private List<ProductCategoryRespVO> dosToVOS(List<ProductCategoryDO> list) {
        List<ProductCategoryRespVO> data = BeanUtils.toBean(list, ProductCategoryRespVO.class);
        Set<Long> shopIds = convertSet(data, ProductCategoryRespVO::getShopId);
        Map<Long, ShopInfoDTO> shops = shopInfoApi.getShopInfoMap(shopIds);
        data.forEach(vo -> {
            ShopInfoDTO shop = shops.get(vo.getShopId());
            vo.setShop(shop == null ? ShopInfoDTO.FALLBACK : shop);
        });
        return data;
    }

    @GetMapping("/list-simple")
    @Operation(summary = "获得产品分类列表（精简信息）", description = "主要用于前端下拉列表")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    @DataPermission(enable = false)
    public CommonResult<List<ProductCategorySimpleRespVO>> getCategorySimpleList(@RequestParam(value = "shopId", required = false) Long shopId) {
        List<ProductCategoryDO> list = new ArrayList<>();
        if (shopId == null || shopId <= 0) {
            shopId = getLoginUserLastShopId();
        }
        if (shopId != null && shopId > 0) {
            list.addAll(productCategoryService.getDescendentCategoryList(shopId, new HashSet<>(), null));
        } else if (isSuperAdmin()) {
            list.addAll(productCategoryService.getAllCategoryList());
        }
        List<ProductCategorySimpleRespVO> data = BeanUtils.toBean(list, ProductCategorySimpleRespVO.class);
        return success(data);
    }

}
